# -*- coding: utf-8 -*-
"""
Module Description: 活动邮件发件
Date: 2017/10/31
Author: FQ
"""
from collections import defaultdict

from pyshare.bll.lang.translate import translate_config_to_dict
from pyshare.const.enums.cross_banquet import CrossBanquetRankKey
from pyshare.const.enums.cross_cate import CrossCateRankKey
from pyshare.const.enums.cross_celadon import CrossCeladonRankKey
from pyshare.const.enums.cross_chess import ChessRankKey
from pyshare.const.enums.cross_contend import CrossContendRankKey
from pyshare.const.enums.cross_fight import CrossFightRankType, CrossFightMatch
from pyshare.const.enums.cross_lottery import CrossLotteryRankKey
from pyshare.const.enums.cross_monopoly import CrossMonopolyRankKey
from pyshare.const.enums.cross_queen import CrossQueenRankKey
from pyshare.const.enums.cross_siegelord_enum import CrossSiegelordRankKey, SiegelordRankType
from pyshare.const.enums.cross_soccer import CrossSoccerRankKey
from pyshare.const.enums.cross_rehearse import CrossRehearseRankKey
from pyshare.const.enums.cross_island_enum import CrossIslandRankKey
from pyshare.const.enums.cross_season_enum import CrossSeasonRankKey
from pyshare.const.enums.cross_clearance_enum import CrossClearanceRankKey
from pyshare.const.enums.cross_fish_enum import CrossFishRankKey
from pyshare.bll.utils.cross.activity_rank.rank_info_utils import CrossChessTeamRankInfo
from pyshare.const.enums.cross_tower import CrossTowerRankKey
from pyshare.dal.gameconfig.query import getProfile
from pyshare.dal.dal_adapters import cross_adapters as cross_adt
from pyshare.dal.dal_adapters import character_adapters as cadts
from pyshare.dal.repository_impl import RoleRepository, CrossActivityExtraAwardRepository
from pyshare.dal.gameconfig.game_env import get_config_env_set, GameConfigEnvLang
from pyshare.utils.rank_utils.cross_fight import cross_fight_rank_component
from pyshare.utils.item_utils import same_award_together
from pyshare.utils.siegelord_rank_utils import siegelord_rank_utils
from pyshare.utils.unique_key import create_idx
from pyshare.core.context import temporary_ctx
from pyshare.const.enums.activity import TypeToCrossRankKey, ActivityClass, ActivityType
from pyshare.const.enums.cross_siege import SiegeRankKey
from pyshare.const.enums.cross_ruins import CrossRuinsRankKey
from pyshare.const.enums.cross_naadam import CrossNaadamRankKey
from pyshare.remote_services.area_services.activity_send import AreaSendActivityService
from pyshare.utils.share_rank_utils import share_leader_board_component
from pyshare.utils.share_rank_utils import normal_rank
from pyshare.utils.season_rank_utils import season_rank_utils
from pyshare.common_logic.final_award_common import FinalAwardCommon
from pyshare.bll.utils.cross.activity_utils import BaseActivityCheck


class RankActivitySendAwardBase(object):
    """
    跨服榜单类活动，未领取邮件发奖基类类
    **增加新的类型活动发件，继承该类时注意以下几点
    1.子类需要定义activity_adapter，record_adapter
    2.确保活动记录/角色领取记录有统一的获取以及修改的方法
    3.如果获取排行数据不一样需要重新定义get_rank_data方法
    """
    activity_adapter = None
    record_adapter = None  # 标记是否领取奖励的适配器

    def __init__(self, activity_id):
        self.have_extra = 0  # 标记活动是否有额外奖励 《额外奖励表center库：TbCrossActivityExtraAward》
        self.activity_id = activity_id  # 活动id
        self.activity = self.get_activity()  # 活动实例
        self.activity_extra = self.get_activity_extra()   # 活动额外奖励
        self.fail_sid_dict = defaultdict(list)  # 邮件失败rid列表
        # 邮件奖励Id字典 /联盟活动表示盟主邮件奖励字典(用于保存相同奖励的邮件奖励id，减少重复创建)
        self.award_id_dict = {}

        self.rid_for_rank = dict()  # {rid: rank}
        self.score_dict = dict()  # {rid: score}
        self.server_for_rids = defaultdict(list)  # {server_id: [rid1, rid2]}
        self.rid_for_service_id = dict()  # {rid: service_id}
        self.activity_class = None

    ###############################################
    @property
    def subject(self):
        return getattr(GameConfigEnvLang(), 'ActivityMailSubject')

    @property
    def content(self):
        return getattr(GameConfigEnvLang(), 'RankActivityContent')

    def get_activity(self):
        """
        返回活动适配器实例
        :return:
        """
        if self.activity_adapter is None:
            raise Exception('activity_adapter of RankActivitySendAward is None')
        return self.activity_adapter.objects.get(ActivityId=self.activity_id)

    def get_activity_extra(self):
        """
        返回活动额外奖励适配器实例
        :return:
        """
        if self.have_extra:
            return CrossActivityExtraAwardRepository.get_by_activity_id(self.activity_id)
        return []

    def get_activity_range_cfg(self):
        """获取排名奖励区间配置"""
        return self.activity.range

    def get_activity_name(self):
        """获取活动名称"""
        # 从TcActivityType表中获取活动名称
        env_key = getProfile('TcActivityType', Class=self.activity_class, Type=self.activity.type).LangEnvKey
        return getattr(GameConfigEnvLang(), env_key)

    def get_award_list_cfg(self):
        """获取活动奖励配置"""
        return self.activity.award

    def get_extra_cfg(self):
        """获取活动奖励配置"""
        return self.activity_extra

    def get_rank_key(self):
        """
        获取榜单key
        :return:
        """
        return TypeToCrossRankKey[self.activity.type]

    def get_rank_list(self, *args, **kwargs):
        """获取榜单"""
        from app.area.core.component_center import ComponentCenter
        area_cc = ComponentCenter()
        start, end = self.get_start_end()
        # 获取榜单数据
        rank_key = area_cc.leader_board.fill_leader_board_key(self.get_rank_key(),
                                                              act_id=self.activity_id)
        rank_data = area_cc.leader_board.get_rank_range(rank_key, start, end, 0, True)
        return rank_data

    def get_rank_data(self):
        """
        初始化  {role_id: 排名}
        :return: {rid: [rank, server_id]}
        """

        rank_data = self.get_rank_list()

        for index, data in enumerate(rank_data):
            self.server_for_rids[data[2]].append(data[0])
            self.rid_for_rank[data[0]] = index + 1
            self.score_dict[data[0]] = int(data[1])

    def get_not_award_record_list(self, rid_list, server_id):
        return self.record_adapter.objects.filter(RoleGuid__in=rid_list, ActivityId=self.activity_id,
                                                  HasRankAward=0, ServerId=server_id)

    def set_record_has_award(self, rid_list, server_id):
        """设置记录为已领取"""
        self.record_adapter.objects.filter(RoleGuid__in=rid_list, ActivityId=self.activity_id,
                                           ServerId=server_id).update(HasRankAward=2)

    ###############################################
    def rank_to_award_index(self, rank):
        """
        返回排名对应的奖励下标
        :param rank:
        :return:
        """
        for w_index, r in enumerate(self.get_activity_range_cfg()):
            if r[0] <= rank <= r[1]:
                return w_index
        return None

    def get_start_end(self):
        """
        返回发奖排名区间 Start, End
        :return:
        """
        range_cfg = self.get_activity_range_cfg()
        return range_cfg[0][0] - 1, range_cfg[-1][-1] - 1

    def get_subject(self):
        name_lang = self.get_activity_name()

        subject = {}
        for code, msg in self.subject.items():
            subject[code] = msg.format(name=name_lang[code])

        return subject

    def get_content(self, rank):
        """
        返回邮件内容
        :param rank:
        :return:
        """
        content = {}
        name_lang = self.get_activity_name()

        for code, msg in self.content.items():
            content[code] = msg.format(name=name_lang[code], rank=rank)

        return content

    @staticmethod
    def get_role_service_id(rid_list):
        """
        返回 role_id_list中 对应角色的 service_id
        :return:
        """
        service_dict = {}
        data_list = RoleRepository.filter_by_rid_list(rid_list, 'RoleGuid', 'ServiceId')
        service_dict.update({r.role_guid: r.service_id for r in data_list})
        return service_dict

    def get_rank_award_cfg(self, rank):
        """
        返回排名对应的奖励配置
        :param rank: 排名
        :return:
        """
        award_index = self.rank_to_award_index(rank)
        if award_index not in self.award_id_dict:
            self.award_id_dict[award_index] = create_idx()

        return self.get_award_list_cfg()[award_index], award_index, self.award_id_dict[award_index]

    def integration_record_by_rank(self, record_list):
        """
        根据排名返回归类的record_list
        :param record_list:
        :return:
        """
        rid_list = list()
        rank_for_records = defaultdict(list)
        for record in record_list:
            rid_list.append(record.role_guid)
            rank = self.rid_for_rank.get(record.role_guid, None)
            if not rank:
                continue
            rank_for_records[rank].append(record)

        return rid_list, rank_for_records

    def response_callback(self, res, s_id_to_role_id_dict, server_id):
        """
        回调结果处理
        发送成功的邮件，将角色领奖记录置成1
        发送失败的邮件，将role_id 计入 fail_sid_dict
        :param res:
        :param s_id_to_role_id_dict: {sid: rid}
        :param server_id: 区服id
        :return:
        """
        if res and 'Success' in res:
            rid_list = [s_id_to_role_id_dict.get(sid) for sid in res['Success']]
            self.set_record_has_award(rid_list, server_id)
            self.fail_sid_dict[server_id] += list(set(s_id_to_role_id_dict.keys()) - set(res['Success']))
        else:
            self.fail_sid_dict[server_id] += s_id_to_role_id_dict.keys()

    def send_single_person_award(self, service_id_dict, rank_dict, server_id):
        """
        发送奖励
        个人排行奖励
        :return:
        """

        for rank, record_list in rank_dict.iteritems():
            # 邮件奖励说明
            content = self.get_content(rank)
            subject = self.get_subject()

            award_list, index, award_id = self.get_rank_award_cfg(rank)
            # 额外奖励内容
            if self.have_extra and self.activity_extra:
                score = self.score_dict.get(record_list[0].role_guid, 0)
                award_index = self.rank_to_award_index(rank)
                extra_award_list = BaseActivityCheck.get_rank_extra_award('', award_index, score, self.activity_extra)
                # 合并普通奖励和额外奖励
                award_list.extend(extra_award_list)
                award_list = same_award_together(award_list)
            s_id_to_role_id_dict = {service_id_dict.get(r.role_guid): r.role_guid for r in record_list}
            # 调用区服服务发送活动奖励
            res_data = AreaSendActivityService.send_rank_activity_award_mail(s_id_to_role_id_dict.keys(), award_list,
                                                                             subject, content, server_id)

            self.response_callback(res_data, s_id_to_role_id_dict, server_id)

    def send_award(self):
        """
        执行发奖
        外部只需要调用该方法就可完成发奖
        :return:
        """
        # 获取榜单排名
        self.get_rank_data()
        for server_id, rid_list in self.server_for_rids.iteritems():
            # 设置上下文
            with temporary_ctx(server_id=server_id):
                # 过滤已领取的玩家
                record_list = self.get_not_award_record_list(rid_list, server_id)
                # 按照排名归类record
                rid_list, record_dict = self.integration_record_by_rank(record_list)

                service_id_dict = self.get_role_service_id(rid_list)
                if not record_list:
                    continue
                # 发送奖励邮件
                self.send_single_person_award(service_id_dict, record_dict, server_id)
        return self.fail_sid_dict


class RankActivitySendAward(RankActivitySendAwardBase):
    """
    跨服冲榜发奖类
    """

    def __init__(self, activity_id):
        self.activity_adapter = cross_adt.CrossRankActivityAdapter
        self.record_adapter = cross_adt.CrossRoleRankActivityRecordAdapter  # 标记是否领取奖励的适配器
        super(RankActivitySendAward, self).__init__(activity_id)
        self.activity_class = ActivityClass.CrossRank


class CrossSiegeSendAward(RankActivitySendAwardBase):
    """
    跨服攻城战发奖类
    """

    def __init__(self, activity_id):
        self.activity_adapter = cross_adt.CrossSiegeActivityAdapter
        self.record_adapter = cross_adt.CrossSiegeRoleRecordAdapter  # 标记是否领取奖励的适配器
        super(CrossSiegeSendAward, self).__init__(activity_id)
        self.have_extra = 1
        self.activity_extra = self.get_activity_extra()   # 活动额外奖励

    ###############################################

    @property
    def content(self):
        return getattr(GameConfigEnvLang(), 'RankMailContent')

    @staticmethod
    def get_rank_name():
        """邮件榜单名称"""
        # return '个人伤害'
        return getattr(GameConfigEnvLang(), 'CrossSiegeDamageRankName')

    def get_content(self, rank):
        """
        返回邮件内容
        :param rank:
        :return:
        """
        content = {}
        name_lang = self.get_activity_name()
        rank_name_lang = self.get_rank_name()

        for code, msg in self.content.items():
            content[code] = msg.format(name=name_lang[code], rank=rank, rank_name=rank_name_lang[code])

        return content

    def get_activity_range_cfg(self):
        """获取排名奖励区间配置"""
        return self.activity.range_list

    def get_activity_name(self):
        """获取活动名称"""
        return getattr(GameConfigEnvLang(), 'CrossSiegeMailSubject')

    def get_award_list_cfg(self):
        """获取活动奖励配置"""
        return self.activity.award_list

    def get_rank_key(self):
        """获取榜单key"""
        return SiegeRankKey.Damage


class ServerRankSendAwardBase(RankActivitySendAwardBase):
    """区服榜单发奖类"""

    def get_rank_list(self, server_id):
        """获取榜单"""
        from app.area.core.component_center import ComponentCenter
        area_cc = ComponentCenter()
        start, end = self.get_start_end()
        # 获取榜单数据
        rank_key = area_cc.leader_board.fill_leader_board_key(self.get_rank_key(),
                                                              act_id=self.activity_id, srv_id=server_id)
        rank_data = area_cc.leader_board.get_rank_range(rank_key, start, end, 0, False)
        return rank_data

    def get_rank_data(self):
        """
        初始化  {role_id: 排名}
        :return: {rid: [rank, server_id]}
        """
        for server_id in self.activity.server_list:
            rank_data = self.get_rank_list(server_id)

            for index, data in enumerate(rank_data):
                self.server_for_rids[server_id].append(data[0])
                self.rid_for_rank[data[0]] = index + 1


class CrossSiegeDonateSendAward(ServerRankSendAwardBase):
    """
    跨服攻城战区服个人贡献榜单发奖
    """

    def __init__(self, activity_id):
        self.activity_adapter = cross_adt.CrossSiegeActivityAdapter
        self.record_adapter = cross_adt.CrossSiegeRoleRecordAdapter  # 标记是否领取奖励的适配器
        super(CrossSiegeDonateSendAward, self).__init__(activity_id)

    @property
    def content(self):
        return getattr(GameConfigEnvLang(), 'RankMailContent')

    @staticmethod
    def get_rank_name():
        """邮件榜单名称"""
        # return '贡献经验'
        return getattr(GameConfigEnvLang(), 'CrossSiegeDonateRankName')

    def get_content(self, rank):
        """
        返回邮件内容
        :param rank:
        :return:
        """
        content = {}
        name_lang = self.get_activity_name()
        rank_name_lang = self.get_rank_name()

        for code, msg in self.content.items():
            content[code] = msg.format(name=name_lang[code], rank=rank, rank_name=rank_name_lang[code])

        return content

    def get_activity_range_cfg(self):
        """获取排名奖励区间配置"""
        return self.activity.donate_range_list

    def get_activity_name(self):
        """获取活动名称"""
        return getattr(GameConfigEnvLang(), 'CrossSiegeMailSubject')

    def get_award_list_cfg(self):
        """获取活动奖励配置"""
        return self.activity.donate_award_list

    def get_rank_key(self):
        """
        获取榜单key
        :return:
        """
        return SiegeRankKey.Donate

    def get_not_award_record_list(self, rid_list, server_id):
        return self.record_adapter.objects.filter(RoleGuid__in=rid_list, ActivityId=self.activity_id,
                                                  HasDonateAward=0, ServerId=server_id)

    def set_record_has_award(self, rid_list, server_id):
        """设置记录为已领取"""
        self.record_adapter.objects.filter(RoleGuid__in=rid_list, ActivityId=self.activity_id,
                                           ServerId=server_id).update(HasDonateAward=2)


class CrossRuinsSendAward(RankActivitySendAwardBase):
    """
    跨服遗迹个人积分榜单发奖
    """

    def __init__(self, activity_id):
        self.activity_adapter = cross_adt.CrossRuinsActivityAdapter
        self.record_adapter = cross_adt.CrossRuinsAwardRoleAdapter  # 标记是否领取奖励的适配器
        super(CrossRuinsSendAward, self).__init__(activity_id)

    ###############################################

    def get_activity(self):
        """
        返回活动适配器实例
        :return:
        """
        if self.activity_adapter is None:
            raise Exception('activity_adapter of RankActivitySendAward is None')
        return self.activity_adapter.objects.get(RuinsId=self.activity_id)

    def get_not_award_record_list(self, rid_list, server_id):
        return self.record_adapter.objects.filter(RoleGuid__in=rid_list, RuinsId=self.activity_id,
                                                  HasPersonalAward=0, SrvId=server_id)

    def set_record_has_award(self, rid_list, server_id):
        """设置记录为已领取"""
        self.record_adapter.objects.filter(RoleGuid__in=rid_list, RuinsId=self.activity_id,
                                           SrvId=server_id).update(HasPersonalAward=2)

    def get_activity_range_cfg(self):
        """获取排名奖励区间配置"""
        return self.activity.personal_range_list

    def get_activity_name(self):
        """获取活动名称"""
        return getattr(GameConfigEnvLang(), 'CrossRuinsMailSubject')

    def get_award_list_cfg(self):
        """获取活动奖励配置"""
        return self.activity.personal_award_list

    def get_rank_key(self):
        """获取榜单key"""
        return CrossRuinsRankKey.PersonalScore


class CrossCateSendAward(RankActivitySendAwardBase):
    """
    跨服美食个人积分榜单发奖
    """

    def __init__(self, activity_id):
        self.activity_adapter = cross_adt.CrossCateActivityAdapter
        self.record_adapter = cross_adt.CrossCateRoleAdapter  # 标记是否领取奖励的适配器
        super(CrossCateSendAward, self).__init__(activity_id)
        self.activity_class = ActivityClass.CrossCate

    ###############################################

    def get_not_award_record_list(self, rid_list, server_id):
        return self.record_adapter.objects.filter(RoleGuid__in=rid_list, ActivityId=self.activity_id,
                                                  HasAward=0, ServerId=server_id)

    def set_record_has_award(self, rid_list, server_id):
        """设置记录为已领取"""
        self.record_adapter.objects.filter(RoleGuid__in=rid_list, ActivityId=self.activity_id,
                                           ServerId=server_id).update(HasAward=2)

    def get_activity_range_cfg(self):
        """获取排名奖励区间配置"""
        return self.activity.range_list

    def get_activity_name(self):
        """获取活动名称"""
        # 从TcActivityType表中获取活动名称
        env_key = getProfile('TcActivityType', Class=self.activity_class, Type=ActivityType.CrossCateTye).LangEnvKey
        return getattr(GameConfigEnvLang(), env_key)

    def get_award_list_cfg(self):
        """获取活动奖励配置"""
        return self.activity.award_list

    def get_rank_key(self):
        """获取榜单key"""
        return CrossCateRankKey.PersonalScore


class CrossChessSendAward(RankActivitySendAwardBase):
    """
    跨服棋局个人积分榜单发奖
    """

    def __init__(self, activity_id):
        self.activity_adapter = cross_adt.CrossChessActivityAdapter
        self.record_adapter = cross_adt.CrossChessRoleAdapter  # 标记是否领取奖励的适配器
        super(CrossChessSendAward, self).__init__(activity_id)
        self.activity_class = ActivityClass.CrossChess
        self.have_extra = 1
        self.activity_extra = self.get_activity_extra()   # 活动额外奖励

    ###############################################

    def get_not_award_record_list(self, rid_list, server_id):
        return self.record_adapter.objects.filter(RoleGuid__in=rid_list, ActivityId=self.activity_id,
                                                  IsGetPersonalAward=0, SrvId=server_id)

    def set_record_has_award(self, rid_list, server_id):
        """设置记录为已领取"""
        self.record_adapter.objects.filter(RoleGuid__in=rid_list, ActivityId=self.activity_id,
                                           SrvId=server_id).update(IsGetPersonalAward=2)

    def get_activity_range_cfg(self):
        """获取排名奖励区间配置"""
        return self.activity.range_list

    def get_activity_name(self):
        """获取活动名称"""
        # 从TcActivityType表中获取活动名称
        env_key = getProfile('TcActivityType', Class=self.activity_class).LangEnvKey
        return getattr(GameConfigEnvLang(), env_key)

    def get_award_list_cfg(self):
        """获取活动奖励配置"""
        return self.activity.award_list

    def get_rank_key(self):
        """获取榜单key"""
        return ChessRankKey.PersonalScore


class CrossChessSendTeamAward(CrossChessSendAward):
    """
    跨服棋局队伍积分榜单发奖
    """

    def __init__(self, activity_id):
        self.activity_adapter = cross_adt.CrossChessActivityAdapter
        self.record_adapter = cross_adt.CrossChessRoleAdapter  # 标记是否领取奖励的适配器
        super(CrossChessSendTeamAward, self).__init__(activity_id)
        self.activity_class = ActivityClass.CrossChess
        self.have_extra = 0
        self.activity_extra = {}   # 活动额外奖励     

    def get_not_award_record_list(self, team_id_list, server_id):
        return self.record_adapter.objects.filter(TeamId__in=team_id_list, ActivityId=self.activity_id,
                                                  IsGetTeamAward=0, SrvId=server_id)

    def set_record_has_award(self, rid_list, server_id):
        """设置记录为已领取"""
        self.record_adapter.objects.filter(RoleGuid__in=rid_list, ActivityId=self.activity_id,
                                           SrvId=server_id).update(IsGetTeamAward=2)

    def get_award_list_cfg(self):
        """获取活动奖励配置"""
        return self.activity.team_award_list

    def get_activity_range_cfg(self):
        """获取排名奖励区间配置"""
        return self.activity.team_range_list

    def get_rank_key(self):
        """获取榜单key"""
        return ChessRankKey.TeamScore

    def get_rank_list(self, *args, **kwargs):
        """
        获取队伍榜单
        :param args:
        :param kwargs:
        :return: [[team_id, score, server_id]]
        """
        start, end = self.get_start_end()
        # 获取榜单数据
        rank_data = CrossChessTeamRankInfo.get_rank_list_info(self.activity_id, start, end, 0)
        return rank_data

    def get_rank_data(self):
        """
        初始化  {role_id: 排名}
        :return: {team_id: [rank, server_id]}
        """

        rank_data = self.get_rank_list()

        for index, data in enumerate(rank_data):
            self.server_for_rids[data[2]].append(data[0])
            self.rid_for_rank[data[0]] = index + 1

    def integration_record_by_rank(self, record_list):
        """
        根据排名返回归类的record_list
        :param record_list:
        :return:
        """
        rid_list = list()
        rank_for_records = defaultdict(list)
        for record in record_list:
            rid_list.append(record.role_guid)
            rank = self.rid_for_rank.get(record.team_id, None)
            if not rank:
                continue
            rank_for_records[rank].append(record)

        return rid_list, rank_for_records

    @property
    def subject(self):
        return getattr(GameConfigEnvLang(), 'ActivityMailSubject')

    @property
    def content(self):
        return getattr(GameConfigEnvLang(), 'CrossChessTeamNotAwardContent')


class CrossSoccerSendChampionAward(RankActivitySendAwardBase):
    """
    跨服足球冠军榜单发奖
    """

    def __init__(self, activity_id):
        self.activity_adapter = cross_adt.CrossSoccerActivityAdapter
        self.record_adapter = cross_adt.CrossSoccerRoleAdapter  # 标记是否领取奖励的适配器
        super(CrossSoccerSendChampionAward, self).__init__(activity_id)
        self.activity_class = ActivityClass.CrossSoccer

    ###############################################

    def get_not_award_record_list(self, rid_list, server_id):
        return self.record_adapter.objects.filter(RoleGuid__in=rid_list, ActivityId=self.activity_id,
                                                  ChampionHadAward=0)

    def set_record_has_award(self, rid_list, server_id):
        """设置记录为已领取"""
        self.record_adapter.objects.filter(RoleGuid__in=rid_list, ActivityId=self.activity_id).update(
            ChampionHadAward=2)

    def get_activity_range_cfg(self):
        """获取排名奖励区间配置"""
        return self.activity.champion_range_list

    def get_activity_name(self):
        """获取活动名称"""
        # 从TcActivityType表中获取活动名称
        env_key = getProfile('TcActivityType', Class=self.activity_class).LangEnvKey
        return getattr(GameConfigEnvLang(), env_key)

    def get_award_list_cfg(self):
        """获取活动奖励配置"""
        return self.activity.champion_award_list

    def get_rank_key(self):
        """获取榜单key"""
        return CrossSoccerRankKey.TeamTotal

    def get_rank_list(self, *args, **kwargs):
        """获取榜单"""
        from app.area.core.component_center import ComponentCenter
        area_cc = ComponentCenter()
        start, end = self.get_start_end()
        champion_team_id = area_cc.soccer_activity.get_champion_team_id(self.activity_id)
        # 获取榜单数据
        rank_key = area_cc.leader_board.fill_leader_board_key(self.get_rank_key(),
                                                              act_id=self.activity_id,
                                                              team_id=champion_team_id)
        rank_data = area_cc.leader_board.get_rank_range(rank_key, start, end, 0, True)
        return rank_data

    @property
    def content(self):
        return getattr(GameConfigEnvLang(), 'CrossSoccerChampionRankContent')


class CrossSoccerSendDonateAward(RankActivitySendAwardBase):
    """
    跨服足球贡献榜单发奖
    """

    def __init__(self, activity_id):
        self.activity_adapter = cross_adt.CrossSoccerActivityAdapter
        self.record_adapter = cross_adt.CrossSoccerRoleAdapter  # 标记是否领取奖励的适配器
        super(CrossSoccerSendDonateAward, self).__init__(activity_id)
        self.activity_class = ActivityClass.CrossSoccer
        self.have_extra = 1
        self.activity_extra = self.get_activity_extra()   # 活动额外奖励

    ###############################################

    def get_not_award_record_list(self, rid_list, server_id):
        return self.record_adapter.objects.filter(RoleGuid__in=rid_list, ActivityId=self.activity_id, TotalHadAward=0)

    def set_record_has_award(self, rid_list, server_id):
        """设置记录为已领取"""
        self.record_adapter.objects.filter(RoleGuid__in=rid_list, ActivityId=self.activity_id).update(TotalHadAward=2)

    def get_activity_range_cfg(self):
        """获取排名奖励区间配置"""
        return self.activity.donate_range_list

    def get_activity_name(self):
        """获取活动名称"""
        # 从TcActivityType表中获取活动名称
        env_key = getProfile('TcActivityType', Class=self.activity_class).LangEnvKey
        return getattr(GameConfigEnvLang(), env_key)

    def get_award_list_cfg(self):
        """获取活动奖励配置"""
        return self.activity.donate_award_list

    def get_rank_key(self):
        """获取榜单key"""
        return CrossSoccerRankKey.AllTeam

    @property
    def content(self):
        return getattr(GameConfigEnvLang(), 'CrossSoccerDonateRankContent')


class CrossRehearseSendHistoryAward(RankActivitySendAwardBase):
    """
    跨服健锐历史最高积分榜单发奖
    """

    def __init__(self, activity_id):
        self.activity_adapter = cross_adt.CrossRehearseActivityAdapter
        self.record_adapter = cross_adt.CrossRehearseRoleRecordAdapter  # 标记是否领取奖励的适配器
        super(CrossRehearseSendHistoryAward, self).__init__(activity_id)
        self.activity_class = ActivityClass.CrossRehearse

    ###############################################

    def get_not_award_record_list(self, rid_list, server_id):
        return self.record_adapter.objects.filter(RoleGuid__in=rid_list, ActivityId=self.activity_id,
                                                  IsGetHistoryHighestAward=0)

    def set_record_has_award(self, rid_list, server_id):
        """设置记录为已领取"""
        self.record_adapter.objects.filter(RoleGuid__in=rid_list,
                                           ActivityId=self.activity_id).update(IsGetHistoryHighestAward=2)

    def get_activity_range_cfg(self):
        """获取排名奖励区间配置"""
        return self.activity.history_range_list

    def get_activity_name(self):
        """获取活动名称"""
        # 从TcActivityType表中获取活动名称
        env_key = getProfile('TcActivityType', Class=self.activity_class).LangEnvKey
        return getattr(GameConfigEnvLang(), env_key)

    def get_award_list_cfg(self):
        """获取活动奖励配置"""
        return self.activity.history_award_list

    def get_rank_key(self):
        """获取榜单key"""
        return CrossRehearseRankKey.HistoryRankKey

    @property
    def content(self):
        return getattr(GameConfigEnvLang(), 'CrossRehearseHistoryRankContent')


class CrossRehearseSendActiveAward(RankActivitySendAwardBase):
    """
    跨服健锐累计榜单发奖
    """

    def __init__(self, activity_id):
        self.activity_adapter = cross_adt.CrossRehearseActivityAdapter
        self.record_adapter = cross_adt.CrossRehearseRoleRecordAdapter  # 标记是否领取奖励的适配器
        super(CrossRehearseSendActiveAward, self).__init__(activity_id)
        self.activity_class = ActivityClass.CrossRehearse
        self.have_extra = 1
        self.activity_extra = self.get_activity_extra()   # 活动额外奖励

    ###############################################

    def get_not_award_record_list(self, rid_list, server_id):
        return self.record_adapter.objects.filter(RoleGuid__in=rid_list, ActivityId=self.activity_id, IsGetTotalAward=0)

    def set_record_has_award(self, rid_list, server_id):
        """设置记录为已领取"""
        self.record_adapter.objects.filter(RoleGuid__in=rid_list, ActivityId=self.activity_id).update(IsGetTotalAward=2)

    def get_activity_range_cfg(self):
        """获取排名奖励区间配置"""
        return self.activity.active_range_list

    def get_activity_name(self):
        """获取活动名称"""
        # 从TcActivityType表中获取活动名称
        env_key = getProfile('TcActivityType', Class=self.activity_class).LangEnvKey
        return getattr(GameConfigEnvLang(), env_key)

    def get_award_list_cfg(self):
        """获取活动奖励配置"""
        return self.activity.active_award_list

    def get_rank_key(self):
        """获取榜单key"""
        return CrossRehearseRankKey.ActiveRankKey

    @property
    def content(self):
        return getattr(GameConfigEnvLang(), 'CrossRehearseActiveRankContent')


class CrossNaadamSendPersonAward(RankActivitySendAwardBase):
    """
    跨服那达慕个人积分榜单发奖
    """

    def __init__(self, activity_id):
        self.activity_adapter = cross_adt.CrossNaadamActivityAdapter
        self.record_adapter = cross_adt.CrossNaadamRoleRecordAdapter  # 标记是否领取奖励的适配器
        super(CrossNaadamSendPersonAward, self).__init__(activity_id)
        self.activity_class = ActivityClass.CrossNaadam
        self.have_extra = 1
        self.activity_extra = self.get_activity_extra()   # 活动额外奖励

    ###############################################

    def get_not_award_record_list(self, rid_list, server_id):
        return self.record_adapter.objects.filter(RoleGuid__in=rid_list, ActivityId=self.activity_id, PersonHasAward=0)

    def set_record_has_award(self, rid_list, server_id):
        """设置记录为已领取"""
        self.record_adapter.objects.filter(RoleGuid__in=rid_list, ActivityId=self.activity_id).update(PersonHasAward=2)

    def get_activity_range_cfg(self):
        """获取排名奖励区间配置"""
        return self.activity.person_range_list

    def get_activity_name(self):
        """获取活动名称"""
        # 从TcActivityType表中获取活动名称
        env_key = getProfile('TcActivityType', Class=self.activity_class).LangEnvKey
        return getattr(GameConfigEnvLang(), env_key)

    def get_award_list_cfg(self):
        """获取活动奖励配置"""
        return self.activity.person_award_list

    def get_rank_key(self):
        """获取榜单key"""
        return CrossNaadamRankKey.PersonalScore

    @property
    def content(self):
        return getattr(GameConfigEnvLang(), 'CrossNaadamPersonRankContent')


class CrossContendSendPersonAward(RankActivitySendAwardBase):
    """
    跨服百家争鸣个人积分榜单发奖
    """

    def __init__(self, activity_id):
        self.activity_adapter = cross_adt.CrossContendActivityAdapter
        self.record_adapter = cross_adt.CrossContendRoleAdapter  # 标记是否领取奖励的适配器
        super(CrossContendSendPersonAward, self).__init__(activity_id)
        self.activity_class = ActivityClass.CrossContend
        self.have_extra = 1
        self.activity_extra = self.get_activity_extra()   # 活动额外奖励

    ###############################################

    def get_not_award_record_list(self, rid_list, server_id):
        return self.record_adapter.objects.filter(
            RoleGuid__in=rid_list, ActivityId=self.activity_id, IsGetPersonAward=0)

    def set_record_has_award(self, rid_list, server_id):
        """设置记录为已领取"""
        self.record_adapter.objects.filter(
            RoleGuid__in=rid_list, ActivityId=self.activity_id).update(IsGetPersonAward=2)

    def get_activity_range_cfg(self):
        """获取排名奖励区间配置"""
        return self.activity.personal_range_list

    def get_activity_name(self):
        """获取活动名称"""
        # 从TcActivityType表中获取活动名称
        env_key = getProfile('TcActivityType', Class=self.activity_class).LangEnvKey
        return getattr(GameConfigEnvLang(), env_key)

    def get_award_list_cfg(self):
        """获取活动奖励配置"""
        return self.activity.personal_award_list

    def get_rank_key(self):
        """获取榜单key"""
        return CrossContendRankKey.PersonalScore

    @property
    def content(self):
        return getattr(GameConfigEnvLang(), 'CrossContendPersonRankContent')


class CrossLotterySendRankAward(RankActivitySendAwardBase):
    """
    跨服抽奖积分榜单发奖
    """

    def __init__(self, activity_id):
        self.activity_adapter = cross_adt.CrossLotteryActivityAdapter
        self.record_adapter = cadts.CrossLotteryRoleAdapter  # 标记是否领取奖励的适配器
        super(CrossLotterySendRankAward, self).__init__(activity_id)
        self.activity_class = ActivityClass.CrossLottery

    ###############################################

    def get_not_award_record_list(self, rid_list, server_id):
        return self.record_adapter.objects.filter(
            RoleGuid__in=rid_list, ActivityId=self.activity_id, IsGetRankAward=0)

    def set_record_has_award(self, rid_list, server_id):
        """设置记录为已领取"""
        self.record_adapter.objects.filter(
            RoleGuid__in=rid_list, ActivityId=self.activity_id).update(IsGetRankAward=2)

    def get_activity_range_cfg(self):
        """获取排名奖励区间配置"""
        return self.activity.range_list

    def get_activity_name(self):
        """获取活动名称"""
        # 从TcActivityType表中获取活动名称
        env_key = getProfile('TcActivityType', Class=self.activity_class, Type=ActivityType.CrossLottery).LangEnvKey
        return getattr(GameConfigEnvLang(), env_key)

    def get_award_list_cfg(self):
        """获取活动排行奖励配置"""
        return self.activity.award_list

    def get_extra_award_list_cfg(self):
        """获取活动额外奖励配置"""
        return self.activity.extra_award_list

    def get_extra_score_list_cfg(self):
        """获取活动额外积分配置"""
        return self.activity.extra_score_list

    def get_rank_key(self):
        """获取榜单key"""
        return CrossLotteryRankKey.LotteryRankKey

    @property
    def content(self):
        return getattr(GameConfigEnvLang(), 'CrossLotteryRankContent')

    def send_single_person_award(self, service_id_dict, rank_dict, server_id):
        """
        发送奖励
        个人排行奖励
        :return:
        """

        for rank, record_list in rank_dict.iteritems():
            # 邮件奖励说明
            content = self.get_content(rank)
            subject = self.get_subject()

            # 排行奖励
            award_list, index, award_id = self.get_rank_award_cfg(rank)

            # 额外奖励
            for r in record_list:
                extra_award_score = self.get_extra_score_list_cfg()[index]
                if r.score >= extra_award_score:
                    award_list.extend(self.get_extra_award_list_cfg()[index])

            s_id_to_role_id_dict = {service_id_dict.get(r.role_guid): r.role_guid for r in record_list}
            # 调用区服服务发送活动奖励
            res_data = AreaSendActivityService.send_rank_activity_award_mail(s_id_to_role_id_dict.keys(), award_list,
                                                                             subject, content, server_id)

            self.response_callback(res_data, s_id_to_role_id_dict, server_id)


class CrossQueenSendFinalAward(RankActivitySendAwardBase):
    """
    跨服如意赠佳人累计积分榜单发奖
    """

    def __init__(self, activity_id):
        self.activity_adapter = cross_adt.CrossQueenActivityAdapter
        self.record_adapter = cross_adt.CrossQueenAwardRoleAdapter  # 标记是否领取奖励的适配器
        super(CrossQueenSendFinalAward, self).__init__(activity_id)
        self.activity_class = ActivityClass.CrossQueen
        self.have_extra = 1
        self.activity_extra = self.get_activity_extra()   # 活动额外奖励

    ###############################################

    def get_not_award_record_list(self, rid_list, server_id):
        return self.record_adapter.objects.filter(RoleGuid__in=rid_list, ActivityId=self.activity_id, HasFinalAward=0)

    def set_record_has_award(self, rid_list, server_id):
        """设置记录为已领取"""
        self.record_adapter.objects.filter(RoleGuid__in=rid_list, ActivityId=self.activity_id).update(HasFinalAward=1)

    def get_activity_range_cfg(self):
        """获取排名奖励区间配置"""
        return self.activity.final_range

    def get_activity_name(self):
        """获取活动名称"""
        # 从TcActivityType表中获取活动名称
        env_key = getProfile('TcActivityType', Class=self.activity_class).LangEnvKey
        return getattr(GameConfigEnvLang(), env_key)

    def get_award_list_cfg(self):
        """获取活动奖励配置"""
        return self.activity.final_award_list

    def get_rank_key(self):
        """获取榜单key"""
        return CrossQueenRankKey.Final

    @property
    def content(self):
        return getattr(GameConfigEnvLang(), 'CrossQueenFinalRankContent')


class CrossQueenSendSingleAward(RankActivitySendAwardBase):
    """
    跨服如意赠佳人单局积分榜单发奖
    """

    def __init__(self, activity_id):
        self.activity_adapter = cross_adt.CrossQueenActivityAdapter
        self.record_adapter = cross_adt.CrossQueenAwardRoleAdapter  # 标记是否领取奖励的适配器
        super(CrossQueenSendSingleAward, self).__init__(activity_id)
        self.activity_class = ActivityClass.CrossQueen

    ###############################################

    def get_not_award_record_list(self, rid_list, server_id):
        return self.record_adapter.objects.filter(RoleGuid__in=rid_list, ActivityId=self.activity_id, HasSingleAward=0)

    def set_record_has_award(self, rid_list, server_id):
        """设置记录为已领取"""
        self.record_adapter.objects.filter(RoleGuid__in=rid_list, ActivityId=self.activity_id).update(HasSingleAward=1)

    def get_activity_range_cfg(self):
        """获取排名奖励区间配置"""
        return self.activity.range

    def get_activity_name(self):
        """获取活动名称"""
        # 从TcActivityType表中获取活动名称
        env_key = getProfile('TcActivityType', Class=self.activity_class).LangEnvKey
        return getattr(GameConfigEnvLang(), env_key)

    def get_award_list_cfg(self):
        """获取活动奖励配置"""
        return self.activity.award_list

    def get_rank_key(self):
        """获取榜单key"""
        return CrossQueenRankKey.Single

    @property
    def content(self):
        return getattr(GameConfigEnvLang(), 'CrossQueenSingleRankContent')


class CrossBanquetSendHistoryAward(RankActivitySendAwardBase):
    """
    跨服满汉全席历史最高积分榜单发奖
    """

    def __init__(self, activity_id):
        self.activity_adapter = cross_adt.CrossBanquetActivityAdapter
        self.record_adapter = cadts.CrossBanquetRoleRecordAdapter  # 标记是否领取奖励的适配器
        super(CrossBanquetSendHistoryAward, self).__init__(activity_id)
        self.activity_class = ActivityClass.CrossBanquet

    ###############################################

    def get_not_award_record_list(self, rid_list, server_id):
        return self.record_adapter.objects.filter(RoleGuid__in=rid_list, ActivityId=self.activity_id,
                                                  IsGetHistoryHighestAward=0)

    def set_record_has_award(self, rid_list, server_id):
        """设置记录为已领取"""
        self.record_adapter.objects.filter(RoleGuid__in=rid_list,
                                           ActivityId=self.activity_id).update(IsGetHistoryHighestAward=2)

    def get_activity_range_cfg(self):
        """获取排名奖励区间配置"""
        return self.activity.history_range_list

    def get_activity_name(self):
        """获取活动名称"""
        # 从TcActivityType表中获取活动名称
        env_key = getProfile('TcActivityType', Class=self.activity_class).LangEnvKey
        return getattr(GameConfigEnvLang(), env_key)

    def get_award_list_cfg(self):
        """获取活动奖励配置"""
        return self.activity.history_award_list

    def get_rank_key(self):
        """获取榜单key"""
        return CrossBanquetRankKey.HistoryRankKey

    @property
    def content(self):
        return getattr(GameConfigEnvLang(), 'CrossBanquetHistoryRankContent')

    def get_rank_list(self, *args, **kwargs):
        """获取榜单"""
        start, end = self.get_start_end()
        # 获取榜单数据
        rank_key = share_leader_board_component.fill_leader_board_key(self.get_rank_key(), act_id=self.activity_id)
        rank_data = share_leader_board_component.get_rank_range(rank_key, start, end, 0,
                                                                share_leader_board_component.RankType.RoleRank)
        return rank_data


class CrossBanquetSendActiveAward(RankActivitySendAwardBase):
    """
    跨服满汉全席累计榜单发奖
    """

    def __init__(self, activity_id):
        self.activity_adapter = cross_adt.CrossBanquetActivityAdapter
        self.record_adapter = cadts.CrossBanquetRoleRecordAdapter  # 标记是否领取奖励的适配器
        super(CrossBanquetSendActiveAward, self).__init__(activity_id)
        self.activity_class = ActivityClass.CrossBanquet
        self.have_extra = 1
        self.activity_extra = self.get_activity_extra()   # 活动额外奖励

    ###############################################

    def get_not_award_record_list(self, rid_list, server_id):
        return self.record_adapter.objects.filter(RoleGuid__in=rid_list, ActivityId=self.activity_id, IsGetTotalAward=0)

    def set_record_has_award(self, rid_list, server_id):
        """设置记录为已领取"""
        self.record_adapter.objects.filter(RoleGuid__in=rid_list, ActivityId=self.activity_id).update(IsGetTotalAward=2)

    def get_activity_range_cfg(self):
        """获取排名奖励区间配置"""
        return self.activity.active_range_list

    def get_activity_name(self):
        """获取活动名称"""
        # 从TcActivityType表中获取活动名称
        env_key = getProfile('TcActivityType', Class=self.activity_class).LangEnvKey
        return getattr(GameConfigEnvLang(), env_key)

    def get_award_list_cfg(self):
        """获取活动奖励配置"""
        return self.activity.active_award_list

    def get_rank_key(self):
        """获取榜单key"""
        return CrossBanquetRankKey.ActiveRankKey

    @property
    def content(self):
        return getattr(GameConfigEnvLang(), 'CrossBanquetActiveRankContent')

    def get_rank_list(self, *args, **kwargs):
        """获取榜单"""
        start, end = self.get_start_end()
        # 获取榜单数据
        rank_key = share_leader_board_component.fill_leader_board_key(self.get_rank_key(), act_id=self.activity_id)
        rank_data = share_leader_board_component.get_rank_range(rank_key, start, end, 0,
                                                                share_leader_board_component.RankType.RoleRank)
        return rank_data


class CrossIslandSendAward(RankActivitySendAwardBase):
    """
    跨服蓬莱仙岛个人榜单奖励发送
    """

    def __init__(self, activity_id):
        self.activity_adapter = cross_adt.CrossIslandActivityAdapter
        self.record_adapter = cross_adt.CrossIslandRoleAdapter  # 标记是否领取奖励的适配器
        super(CrossIslandSendAward, self).__init__(activity_id)
        self.activity_class = ActivityClass.CrossIsland

    ###############################################

    def get_not_award_record_list(self, rid_list, server_id):
        return self.record_adapter.objects.filter(RoleGuid__in=rid_list, ActivityId=self.activity_id, PersonHasAward=0)

    def set_record_has_award(self, rid_list, server_id):
        """设置记录为已领取"""
        self.record_adapter.objects.filter(RoleGuid__in=rid_list, ActivityId=self.activity_id).update(PersonHasAward=2)

    def get_activity_range_cfg(self):
        """获取排名奖励区间配置"""
        return self.activity.range_list

    def get_activity_name(self):
        """获取活动名称"""
        # 从TcActivityType表中获取活动名称
        env_key = getProfile('TcActivityType', Class=self.activity_class).LangEnvKey
        return getattr(GameConfigEnvLang(), env_key)

    def get_award_list_cfg(self):
        """获取活动奖励配置"""
        return self.activity.award_list

    def get_rank_key(self):
        """获取榜单key"""
        return CrossIslandRankKey.PersonScore

    def get_rank_list(self, *args, **kwargs):
        """获取榜单"""
        start, end = self.get_start_end()
        # 获取榜单数据
        rank_key = share_leader_board_component.fill_leader_board_key(self.get_rank_key(),
                                                                      activity_id=self.activity_id)
        rank_data = share_leader_board_component.get_rank_range(rank_key, start, end, 0,
                                                                share_leader_board_component.RankType.RoleRank)
        return rank_data

    def send_single_person_award(self, service_id_dict, rank_dict, server_id):
        """
        发送奖励
        个人排行奖励
        :return:
        """

        for rank, record_list in rank_dict.iteritems():
            # 邮件奖励说明
            content = self.get_content(rank)
            subject = self.get_subject()
            score = 0  # 玩家分数
            # rank_dict{排名: record_list, 2: record_list}
            # 每个record_list存放一个玩家的角色信息: [CrossIslandRoleRecord]
            if record_list:
                island_role = record_list[0]
                score = island_role.score
            award_list, index, award_id = self.get_rank_award_cfg(rank, score)
            s_id_to_role_id_dict = {service_id_dict.get(r.role_guid): r.role_guid for r in record_list}
            # 调用区服服务发送活动奖励
            res_data = AreaSendActivityService.send_rank_activity_award_mail(s_id_to_role_id_dict.keys(), award_list,
                                                                             subject, content, server_id)

            self.response_callback(res_data, s_id_to_role_id_dict, server_id)

    def get_rank_award_cfg(self, rank, score=0):
        """
        返回排名对应的奖励配置
        :param rank: 排名
        :return:
        """
        award_index = self.rank_to_award_index(rank)
        if award_index not in self.award_id_dict:
            self.award_id_dict[award_index] = create_idx()
        award_list = self.get_award_list_cfg()[award_index]

        # 判断是否有额外奖励可领取
        extra_award_list = []
        if award_index < len(self.activity.extra_score_list):
            if ((score >= self.activity.extra_score_list[award_index])
                    and award_index < len(self.activity.extra_award_list)):
                extra_award_list = self.activity.extra_award_list[award_index]
        # 拼接最终下发奖励
        if extra_award_list:
            award_list += extra_award_list
        return award_list, award_index, self.award_id_dict[award_index]

    def get_rank_data(self):
        """
        初始化  {role_id: 排名}
        :return: {rid: [rank, server_id]}
        """

        rank_data = self.get_rank_list()

        for index, data in enumerate(rank_data):
            self.server_for_rids[data[2]].append(data[0])
            self.rid_for_rank[data[0]] = index + 1

    @property
    def content(self):
        return getattr(GameConfigEnvLang(), 'CrossIslandPersonRankContent')


class CrossSeasonRankSendAward(RankActivitySendAwardBase):
    """
    九州之巅赛季总榜邮件补发
    """
    def __init__(self, activity_id):
        # 此处activity_id指season_id赛季id
        self.activity_adapter = cross_adt.CrossSeasonActivityAdapter
        self.record_adapter = cross_adt.CrossSeasonRoleAdapter  # 标记是否领取奖励的适配器
        super(CrossSeasonRankSendAward, self).__init__(activity_id)
        self.activity_class = ActivityClass.CrossSeason
        self.step = 5000  # 每次从总榜单最多读取数据数目

    ###############################################
    def get_activity(self):
        """
        返回活动适配器实例
        :return:
        """
        if self.activity_adapter is None:
            raise Exception('activity_adapter of RankActivitySendAward is None')
        return self.activity_adapter.objects.get(SeasonId=self.activity_id)

    def get_not_award_record_list(self, rid_list, server_id):
        return self.record_adapter.objects.filter(RoleGuid__in=rid_list, SeasonId=self.activity_id, SeasonHasAward=0)

    def set_record_has_award(self, rid_list, server_id):
        """设置记录为已领取"""
        self.record_adapter.objects.filter(RoleGuid__in=rid_list, SeasonId=self.activity_id).update(SeasonHasAward=2)

    def get_activity_range_cfg(self):
        """获取排名奖励区间配置"""
        return self.activity.range_list

    def get_activity_name(self):
        """获取活动名称"""
        # 从TcActivityType表中获取活动名称
        env_key = getProfile('TcActivityType', Class=self.activity_class).LangEnvKey
        return getattr(GameConfigEnvLang(), env_key)

    def get_award_list_cfg(self):
        """获取活动奖励配置"""
        return self.activity.award_list

    def get_rank_key(self):
        """获取榜单key"""
        return CrossSeasonRankKey.SeasonRank

    def get_rank_list(self, *args, **kwargs):
        """获取榜单"""
        start, end = self.get_start_end()
        # 获取榜单数据
        # 由于榜单数据过于庞大, 需要切割获取
        rank_key = normal_rank.fill_leader_board_key(self.get_rank_key(), season_id=self.activity_id)
        index = start
        rank_list = []
        while index <= end:
            cur_start = index
            cur_end = index + self.step - 1
            if cur_end > end:
                cur_end = end
            rank_data = normal_rank.get_rank_range(rank_key, cur_start, cur_end, 0, normal_rank.RankType.RoleRank, need_dan=False)
            if rank_data:
                rank_list.extend(rank_data)
            index += self.step
        return rank_list

    def get_rank_data(self):
        """
        初始化  {role_id: 排名}
        :return: {rid: [rank, server_id]}
        """

        rank_data = self.get_rank_list()

        for index, data in enumerate(rank_data):
            self.server_for_rids[data[2]].append(data[0])
            self.rid_for_rank[data[0]] = index + 1

    def send_award(self):
        """
        执行发奖
        外部只需要调用该方法就可完成发奖
        :return:
        """
        # 获取榜单排名
        self.get_rank_data()
        for server_id, rid_list in self.server_for_rids.iteritems():
            # 设置上下文
            with temporary_ctx(server_id=server_id):
                # 过滤已领取的玩家
                record_list = self.get_not_award_record_list(rid_list, server_id)
                # 按照排名归类record
                rid_list, record_dict = self.integration_record_by_rank(record_list)

                service_id_dict = self.get_role_service_id(rid_list)
                if not record_list:
                    continue
                # 发送奖励邮件
                self.send_single_person_award(service_id_dict, record_dict, server_id)
        return self.fail_sid_dict

    @property
    def content(self):
        return getattr(GameConfigEnvLang(), 'CrossIslandSeasonRankContent')


class CrossSeasonGroupRankSendAward(RankActivitySendAwardBase):
    """
    九州之巅分赛区榜邮件补发
    """
    def __init__(self, activity_id, stage_id):
        # 此处activity_id指season_id赛季id
        self.activity_adapter = cross_adt.CrossSeasonActivityAdapter
        self.record_adapter = cross_adt.CrossSeasonRoleAdapter  # 标记是否领取奖励的适配器
        # self.history_record_adapter = cross_adt.CrossSeasonStageAwardHistoryAdapter  # 记录阶段榜单奖励领取
        super(CrossSeasonGroupRankSendAward, self).__init__(activity_id)
        self.activity_class = ActivityClass.CrossSeason
        self.stage_id = stage_id  # 阶段id

    ###############################################
    def get_activity(self):
        """
        返回活动适配器实例
        :return:
        """
        if self.activity_adapter is None:
            raise Exception('activity_adapter of RankActivitySendAward is None')
        return self.activity_adapter.objects.get(SeasonId=self.activity_id)

    def get_not_award_record_list(self, rid_list, server_id):
        return self.record_adapter.objects.filter(RoleGuid__in=rid_list, SeasonId=self.activity_id, StageHasAward__lt=self.stage_id)

    def set_record_has_award(self, rid_list, server_id):
        """设置记录为已领取"""
        # 标记奖励已领取
        self.record_adapter.objects.filter(RoleGuid__in=rid_list, SeasonId=self.activity_id).update(StageHasAward=self.stage_id)
        # 记录非赛区榜单奖励领取记录
        from pyshare.dal.repository_impl import CrossSeasonStageAwardHistoryRepository
        from pyshare.const.enums.cross_season_enum import StageAwardStatus
        CrossSeasonStageAwardHistoryRepository.create_many(
            [{'RoleGuid': rid, 'SeasonId': self.activity_id, 'StageId': self.stage_id,
              'AwardStatus': StageAwardStatus.Award} for rid in rid_list])

    def get_activity_range_cfg(self):
        """获取排名奖励区间配置"""
        return self.activity.range_list

    def get_activity_name(self):
        """获取活动名称"""
        # 从TcActivityType表中获取活动名称
        env_key = getProfile('TcActivityType', Class=self.activity_class).LangEnvKey
        return getattr(GameConfigEnvLang(), env_key)

    def get_award_list_cfg(self):
        """获取活动奖励配置"""
        return self.activity.award_list

    def get_rank_key(self):
        """获取榜单key"""
        return CrossSeasonRankKey.SeasonGroupRank

    def get_rank_key_list(self):
        """获取缓存中所有分赛区榜单key"""
        group_rank_key_list = season_rank_utils.get_group_rank_key_list(season_id=self.activity_id,
                                                                        stage_id=self.stage_id)
        return group_rank_key_list

    def get_rank_list(self, *args, **kwargs):
        """
        获取榜单
        rank_list每个下标存放的是一个分赛区榜单的玩家
        其中rid1和rid2在同一榜单, rid3在另一个榜单
        [[['rid1', 500, '19'], ['rid2', 300, '19']], [['rid3', 999, '19']]]
        """
        start, end = self.get_start_end()
        rank_key_list = self.get_rank_key_list()
        rank_list = []
        # 将所有分赛区榜单的数据汇总
        for rank_key in rank_key_list:
            # 获取榜单数据
            rank_data = normal_rank.get_rank_range(rank_key, start, end, 0, normal_rank.RankType.RoleRank, need_dan=False)
            rank_list.append(rank_data)
        return rank_list

    @property
    def content(self):
        return getattr(GameConfigEnvLang(), 'CrossIslandSeasonGroupRankContent')

    def get_rank_data(self):
        """
        初始化  {role_id: 排名}
        :return: {rid: [rank, server_id]}
        """

        rank_data_list = self.get_rank_list()

        for rank_data in rank_data_list:
            for index, data in enumerate(rank_data):
                self.server_for_rids[data[2]].append(data[0])
                self.rid_for_rank[data[0]] = index + 1

    def send_award(self):
        """
        执行发奖
        外部只需要调用该方法就可完成发奖
        :return:
        """
        # 获取榜单排名
        self.get_rank_data()
        for server_id, rid_list in self.server_for_rids.iteritems():
            # 设置上下文
            with temporary_ctx(server_id=server_id):
                # 过滤已领取的玩家
                record_list = self.get_not_award_record_list(rid_list, server_id)
                # 按照排名归类record
                rid_list, record_dict = self.integration_record_by_rank(record_list)

                service_id_dict = self.get_role_service_id(rid_list)
                if not record_list:
                    continue
                # 发送奖励邮件
                self.send_single_person_award(service_id_dict, record_dict, server_id)
        return self.fail_sid_dict


class CrossClearanceSendAward(RankActivitySendAwardBase):
    """
    跨服三消个人榜单奖励发送
    """

    def __init__(self, activity_id):
        self.activity_adapter = cross_adt.CrossClearanceActivityAdapter
        self.record_adapter = cadts.CrossClearanceRoleAdapter  # 标记是否领取奖励的适配器
        super(CrossClearanceSendAward, self).__init__(activity_id)
        self.activity_class = ActivityClass.CrossClearance

    ###############################################

    def get_not_award_record_list(self, rid_list, server_id):
        return self.record_adapter.objects.filter(RoleGuid__in=rid_list, ActivityId=self.activity_id, HasAward=0)

    def set_record_has_award(self, rid_list, server_id):
        """设置记录为已领取"""
        self.record_adapter.objects.filter(RoleGuid__in=rid_list, ActivityId=self.activity_id).update(HasAward=2)

    def get_activity_range_cfg(self):
        """获取排名奖励区间配置"""
        return self.activity.range_list

    def get_activity_name(self):
        """获取活动名称"""
        # 从TcActivityType表中获取活动名称
        env_key = getProfile('TcActivityType', Class=self.activity_class).LangEnvKey
        return getattr(GameConfigEnvLang(), env_key)

    def get_award_list_cfg(self):
        """获取活动奖励配置"""
        return self.activity.award_list

    def get_rank_key(self):
        """获取榜单key"""
        return CrossClearanceRankKey.PersonScore

    def get_rank_list(self, *args, **kwargs):
        """获取榜单"""
        start, end = self.get_start_end()
        # 获取榜单数据
        rank_key = share_leader_board_component.fill_leader_board_key(self.get_rank_key(),
                                                                      act_id=self.activity_id)
        rank_data = share_leader_board_component.get_rank_range(rank_key, start, end, 0,
                                                                share_leader_board_component.RankType.RoleRank)
        return rank_data

    def send_single_person_award(self, service_id_dict, rank_dict, server_id):
        """
        发送奖励
        个人排行奖励
        :return:
        """

        for rank, record_list in rank_dict.iteritems():
            # 邮件奖励说明
            content = self.get_content(rank)
            subject = self.get_subject()
            score = 0  # 玩家分数
            # rank_dict{排名: record_list, 2: record_list}
            # 每个record_list存放一个玩家的角色信息: [CrossClearanceRoleRecord]
            if record_list:
                island_role = record_list[0]
                score = island_role.total_score
            award_list, index, award_id = self.get_rank_award_cfg(rank, score)
            s_id_to_role_id_dict = {service_id_dict.get(r.role_guid): r.role_guid for r in record_list}
            # 调用区服服务发送活动奖励
            res_data = AreaSendActivityService.send_rank_activity_award_mail(s_id_to_role_id_dict.keys(), award_list,
                                                                             subject, content, server_id)

            self.response_callback(res_data, s_id_to_role_id_dict, server_id)

    def get_rank_award_cfg(self, rank, score=0):
        """
        返回排名对应的奖励配置
        :param rank: 排名
        :return:
        """
        award_index = self.rank_to_award_index(rank)
        if award_index not in self.award_id_dict:
            self.award_id_dict[award_index] = create_idx()
        award_list = self.get_award_list_cfg()[award_index]

        # 判断是否有额外奖励可领取
        extra_award_list = []
        if award_index < len(self.activity.extra_score_list):
            if ((score >= self.activity.extra_score_list[award_index])
                    and award_index < len(self.activity.extra_award_list)):
                extra_award_list = self.activity.extra_award_list[award_index]
        # 拼接最终下发奖励
        if extra_award_list:
            award_list += extra_award_list
        return award_list, award_index, self.award_id_dict[award_index]

    def get_rank_data(self):
        """
        初始化  {role_id: 排名}
        :return: {rid: [rank, server_id]}
        """

        rank_data = self.get_rank_list()

        for index, data in enumerate(rank_data):
            self.server_for_rids[data[2]].append(data[0])
            self.rid_for_rank[data[0]] = index + 1

    @property
    def content(self):
        return getattr(GameConfigEnvLang(), 'CrossClearancePersonRankContent')


class CrossClearanceSendFinalAward(object):
    """
    跨服三消终极奖励发送
    """

    def __init__(self, activity_id):
        self.activity_adapter = cross_adt.CrossClearanceActivityAdapter
        self.record_adapter = cadts.CrossClearanceRoleAdapter  # 标记是否领取奖励的适配器
        self.activity_class = ActivityClass.CrossClearance
        self.activity_id = activity_id
        self.activity = self.activity_adapter.objects.get(ActivityId=self.activity_id)

    ###############################################

    def is_not_award(self, rid):
        return self.record_adapter.objects.get(RoleGuid=rid, ActivityId=self.activity_id, FinalHasAward=0)

    def set_record_has_award(self, rid):
        """设置记录为已领取"""
        self.record_adapter.objects.filter(RoleGuid=rid, ActivityId=self.activity_id).update(FinalHasAward=2)

    def get_activity_name(self):
        """获取活动名称"""
        # 从TcActivityType表中获取活动名称
        env_key = getProfile('TcActivityType', Class=self.activity_class).LangEnvKey
        return getattr(GameConfigEnvLang(), env_key)

    def get_award(self):
        """获取活动奖励配置"""
        return self.activity.final_award_list

    def get_rank_key(self):
        """获取榜单Key"""
        # 获取榜单数据
        rank_key = share_leader_board_component.fill_leader_board_key(CrossClearanceRankKey.PersonScore,
                                                                      act_id=self.activity_id)
        return rank_key

    def get_gainer_info(self):
        """
        获取终极奖励获得者
        :return: {[rid, score, server_id]}
        """
        gainer_info = FinalAwardCommon.has_final_award_by_type(ActivityType.CrossClearance, self.get_rank_key())
        return gainer_info

    @property
    def content(self):
        return getattr(GameConfigEnvLang(), 'CrossClearanceFinalAwardContent')

    @property
    def subject(self):
        return getattr(GameConfigEnvLang(), 'ActivityMailSubject')

    def get_content(self):
        name_lang = self.get_activity_name()
        content = {}
        for code, msg in self.content.items():
            content[code] = msg.format(name=name_lang[code])

        return content

    def get_subject(self):
        name_lang = self.get_activity_name()
        subject = {}
        for code, msg in self.subject.items():
            subject[code] = msg.format(name=name_lang[code])

        return subject

    def send_award(self):
        """
        执行发奖
        外部只需要调用该方法就可完成发奖
        :return:
        """
        # 获取获得者
        gainer_info = self.get_gainer_info()
        if gainer_info:
            rid, score, server_id = gainer_info     # 获得者信息
            # 设置上下文
            with temporary_ctx(server_id=server_id):
                if self.is_not_award(rid):
                    # 邮件奖励说明
                    content = self.get_content()
                    subject = self.get_subject()
                    # 发送奖励邮件
                    service_id = RoleRepository.get_by_rid(rid, "ServiceId").service_id
                    # 调用区服服务发送活动奖励
                    res_data = AreaSendActivityService.send_rank_activity_award_mail([service_id],
                                                                                     self.get_award(),
                                                                                     subject, content, server_id)
                    # 设置已经领取
                    if res_data and 'Success' in res_data:
                        if service_id in res_data["Success"]:
                            self.set_record_has_award(rid)
        return


class CrossMonopolySendAward(RankActivitySendAwardBase):
    """
    跨服大富翁个人榜单奖励发送
    """

    def __init__(self, activity_id):
        self.activity_adapter = cross_adt.CrossMonopolyActivityAdapter
        self.record_adapter = cadts.CrossMonopolyRoleAdapter  # 标记是否领取奖励的适配器
        super(CrossMonopolySendAward, self).__init__(activity_id)
        self.activity_class = ActivityClass.CrossMonopoly

    ###############################################

    def get_not_award_record_list(self, rid_list, server_id):
        return self.record_adapter.objects.filter(RoleGuid__in=rid_list, ActivityId=self.activity_id, IsGetPersonAward=0)

    def set_record_has_award(self, rid_list, server_id):
        """设置记录为已领取"""
        self.record_adapter.objects.filter(RoleGuid__in=rid_list, ActivityId=self.activity_id).update(IsGetPersonAward=2)

    def get_activity_range_cfg(self):
        """获取排名奖励区间配置"""
        return self.activity.person_range_list

    def get_activity_name(self):
        """获取活动名称"""
        # 从TcActivityType表中获取活动名称
        env_key = getProfile('TcActivityType', Class=self.activity_class).LangEnvKey
        return getattr(GameConfigEnvLang(), env_key)

    def get_award_list_cfg(self):
        """获取活动奖励配置"""
        return self.activity.person_award_list

    def get_rank_key(self):
        """获取榜单key"""
        return CrossMonopolyRankKey.PersonRankKey

    def get_rank_list(self, *args, **kwargs):
        """获取榜单"""
        start, end = self.get_start_end()
        # 获取榜单数据
        rank_key = share_leader_board_component.fill_leader_board_key(self.get_rank_key(),
                                                                      act_id=self.activity_id)
        rank_data = share_leader_board_component.get_rank_range(rank_key, start, end, 0,
                                                                share_leader_board_component.RankType.RoleRank)
        return rank_data

    def send_single_person_award(self, service_id_dict, rank_dict, server_id):
        """
        发送奖励
        个人排行奖励
        :return:
        """

        for rank, record_list in rank_dict.iteritems():
            # 邮件奖励说明
            content = self.get_content(rank)
            subject = self.get_subject()
            score = 0  # 玩家分数
            # rank_dict{排名: record_list, 2: record_list}
            # 每个record_list存放一个玩家的角色信息: [CrossIslandRoleRecord]
            if record_list:
                island_role = record_list[0]
                score = island_role.score
            award_list, index, award_id = self.get_rank_award_cfg(rank, score)
            s_id_to_role_id_dict = {service_id_dict.get(r.role_guid): r.role_guid for r in record_list}
            # 调用区服服务发送活动奖励
            res_data = AreaSendActivityService.send_rank_activity_award_mail(s_id_to_role_id_dict.keys(), award_list,
                                                                             subject, content, server_id)

            self.response_callback(res_data, s_id_to_role_id_dict, server_id)

    def get_rank_award_cfg(self, rank, score=0):
        """
        返回排名对应的奖励配置
        :param rank: 排名
        :param score: 需求积分
        :return:
        """
        award_index = self.rank_to_award_index(rank)
        if award_index not in self.award_id_dict:
            self.award_id_dict[award_index] = create_idx()
        award_list = self.get_award_list_cfg()[award_index]

        # 判断是否有额外奖励可领取
        extra_award_list = []
        if award_index < len(self.activity.person_extra_score_list):
            if ((score >= self.activity.person_extra_score_list[award_index])
                    and award_index < len(self.activity.person_extra_award_list)):
                extra_award_list = self.activity.person_extra_award_list[award_index]
        # 拼接最终下发奖励
        if extra_award_list:
            award_list += extra_award_list
        return award_list, award_index, self.award_id_dict[award_index]

    def get_rank_data(self):
        """
        初始化  {role_id: 排名}
        :return: {rid: [rank, server_id]}
        """

        rank_data = self.get_rank_list()

        for index, data in enumerate(rank_data):
            self.server_for_rids[data[2]].append(data[0])
            self.rid_for_rank[data[0]] = index + 1

    @property
    def content(self):
        return getattr(GameConfigEnvLang(), 'CrossMonopolyPersonRankContent')


class CrossSiegelordSendAward(RankActivitySendAwardBase):
    """
    跨服攻城略地个人榜单奖励发送
    """

    def __init__(self, activity_id):
        self.activity_adapter = cross_adt.CrossSiegelordActivityAdapter
        self.field_adapter = cross_adt.CrossSiegelordFieldAdapter  # 战场活动适配器
        self.record_adapter = cross_adt.CrossSiegelordRoleAdapter  # 标记是否领取奖励的适配器
        super(CrossSiegelordSendAward, self).__init__(activity_id)
        self.field_activity = self.get_field_activity()
        self.activity_class = ActivityClass.CrossSiegelord

    ###############################################
    def get_field_activity(self):
        """
        返回战场活动适配器实例
        :return:
        """
        if self.field_adapter is None:
            raise Exception('field_adapter of RankActivitySendAward is None')
        return self.field_adapter.objects.get(FieldId=self.activity.field_id)

    def get_not_award_record_list(self, rid_list, server_id):
        return self.record_adapter.objects.filter(RoleGuid__in=rid_list, ActivityId=self.activity_id, HasPersonAward=0)

    def set_record_has_award(self, rid_list, server_id):
        """设置记录为已领取"""
        self.record_adapter.objects.filter(RoleGuid__in=rid_list, ActivityId=self.activity_id).update(HasPersonAward=1)

    def get_activity_range_cfg(self):
        """获取排名奖励区间配置"""
        return self.field_activity.person_range_list

    def get_activity_name(self):
        """获取活动名称"""
        # 从TcActivityType表中获取活动名称
        env_key = getProfile('TcActivityType', Class=self.activity_class).LangEnvKey
        return getattr(GameConfigEnvLang(), env_key)

    def get_award_list_cfg(self):
        """获取活动奖励配置"""
        return self.field_activity.person_award_list

    def get_rank_key(self):
        """获取榜单key"""
        return CrossSiegelordRankKey.SiegelordPersonScoreRank

    def get_rank_list(self, *args, **kwargs):
        """获取榜单"""
        start, end = self.get_start_end()
        rank_key = siegelord_rank_utils.fill_leader_board_key(CrossSiegelordRankKey.SiegelordPersonScoreRank,
                                                              activity_id=self.activity_id)
        # 获取榜单数据
        rank_data = siegelord_rank_utils.get_range_by_two_value(rank_key, start, end)
        return rank_data

    def get_rank_award_cfg(self, rank, score=0):
        """
        返回排名对应的奖励配置
        :param rank: 排名
        :return:
        """
        award_index = self.rank_to_award_index(rank)
        if award_index not in self.award_id_dict:
            self.award_id_dict[award_index] = create_idx()
        award_list = self.get_award_list_cfg()[award_index]

        # 判断是否有额外奖励可领取
        extra_award_list = []
        if award_index < len(self.field_activity.extra_score_list):
            if ((score >= self.field_activity.extra_score_list[award_index])
                    and award_index < len(self.field_activity.extra_award_list)):
                extra_award_list = self.field_activity.extra_award_list[award_index]
        # 拼接最终下发奖励
        if extra_award_list:
            award_list += extra_award_list
        return award_list, award_index, self.award_id_dict[award_index]

    def get_rank_data(self):
        """
        初始化
        :return:
        """

        rank_data = self.get_rank_list()

        for index, data in enumerate(rank_data):
            self.server_for_rids[data[2]].append(data[0])
            self.rid_for_rank[data[0]] = index + 1

    @property
    def content(self):
        return getattr(GameConfigEnvLang(), 'SiegelordPersonRankContent')

    def get_extra_award_list_cfg(self):
        """获取活动额外奖励配置"""
        return self.field_activity.extra_award_list

    def get_extra_score_list_cfg(self):
        """获取活动额外积分配置"""
        return self.field_activity.extra_score_list

    def send_single_person_award(self, service_id_dict, rank_dict, server_id):
        """
        发送奖励
        个人排行奖励
        :return:
        """

        for rank, record_list in rank_dict.iteritems():
            # 邮件奖励说明
            content = self.get_content(rank)
            subject = self.get_subject()
            score = 0  # 玩家分数
            if record_list:
                siegelord_role = record_list[0]
                score = siegelord_role.person_score
            # 排行奖励
            award_list, index, award_id = self.get_rank_award_cfg(rank, score)

            s_id_to_role_id_dict = {service_id_dict.get(r.role_guid): r.role_guid for r in record_list}
            # 调用区服服务发送活动奖励
            res_data = AreaSendActivityService.send_rank_activity_award_mail(s_id_to_role_id_dict.keys(), award_list,
                                                                             subject, content, server_id)

            self.response_callback(res_data, s_id_to_role_id_dict, server_id)


class CrossCeladonSendAward(RankActivitySendAwardBase):
    """
    跨服青瓷御器个人榜单奖励发送
    """

    def __init__(self, activity_id):
        self.activity_adapter = cross_adt.CrossCeladonActivityAdapter
        self.record_adapter = cross_adt.CrossCeladonRoleAdapter  # 标记是否领取奖励的适配器
        super(CrossCeladonSendAward, self).__init__(activity_id)
        self.activity_class = ActivityClass.CrossCeladon

    ###############################################

    def get_not_award_record_list(self, rid_list, server_id):
        return self.record_adapter.objects.filter(RoleGuid__in=rid_list, ActivityId=self.activity_id, IsGetPersonAward=0)

    def set_record_has_award(self, rid_list, server_id):
        """设置记录为已领取"""
        self.record_adapter.objects.filter(RoleGuid__in=rid_list, ActivityId=self.activity_id).update(IsGetPersonAward=2)

    def get_activity_range_cfg(self):
        """获取排名奖励区间配置"""
        return self.activity.person_range_list

    def get_activity_name(self):
        """获取活动名称"""
        # 从TcActivityType表中获取活动名称
        env_key = getProfile('TcActivityType', Class=self.activity_class).LangEnvKey
        return getattr(GameConfigEnvLang(), env_key)

    def get_award_list_cfg(self):
        """获取活动奖励配置"""
        return self.activity.person_award_list

    def get_rank_key(self):
        """获取榜单key"""
        return CrossCeladonRankKey.PersonRankKey

    def get_rank_list(self, *args, **kwargs):
        """获取榜单"""
        start, end = self.get_start_end()
        # 获取榜单数据
        rank_key = share_leader_board_component.fill_leader_board_key(self.get_rank_key(),
                                                                      act_id=self.activity_id)
        rank_data = share_leader_board_component.get_rank_range(rank_key, start, end, 0,
                                                                share_leader_board_component.RankType.RoleRank)
        return rank_data

    def send_single_person_award(self, service_id_dict, rank_dict, server_id):
        """
        发送奖励
        个人排行奖励
        :return:
        """

        for rank, record_list in rank_dict.iteritems():
            # 邮件奖励说明
            content = self.get_content(rank)
            subject = self.get_subject()
            score = 0  # 玩家分数
            # rank_dict{排名: record_list, 2: record_list}
            # 每个record_list存放一个玩家的角色信息: [CrossIslandRoleRecord]
            if record_list:
                island_role = record_list[0]
                score = island_role.score
            award_list, index, award_id = self.get_rank_award_cfg(rank, score)
            s_id_to_role_id_dict = {service_id_dict.get(r.role_guid): r.role_guid for r in record_list}
            # 调用区服服务发送活动奖励
            res_data = AreaSendActivityService.send_rank_activity_award_mail(s_id_to_role_id_dict.keys(), award_list,
                                                                             subject, content, server_id)

            self.response_callback(res_data, s_id_to_role_id_dict, server_id)

    def get_rank_award_cfg(self, rank, score=0):
        """
        返回排名对应的奖励配置
        :param rank: 排名
        :param score: 需求积分
        :return:
        """
        award_index = self.rank_to_award_index(rank)
        if award_index not in self.award_id_dict:
            self.award_id_dict[award_index] = create_idx()
        award_list = self.get_award_list_cfg()[award_index]

        # 判断是否有额外奖励可领取
        extra_award_list = []
        if award_index < len(self.activity.person_extra_score_list):
            if ((score >= self.activity.person_extra_score_list[award_index])
                    and award_index < len(self.activity.person_extra_award_list)):
                extra_award_list = self.activity.person_extra_award_list[award_index]
        # 拼接最终下发奖励
        if extra_award_list:
            award_list += extra_award_list
        return award_list, award_index, self.award_id_dict[award_index]

    def get_rank_data(self):
        """
        初始化  {role_id: 排名}
        :return: {rid: [rank, server_id]}
        """

        rank_data = self.get_rank_list()

        for index, data in enumerate(rank_data):
            self.server_for_rids[data[2]].append(data[0])
            self.rid_for_rank[data[0]] = index + 1

    @property
    def content(self):
        return getattr(GameConfigEnvLang(), 'CrossCeladonPersonRankContent')


class CrossCeladonSendFinalAward(object):
    """
    跨服青瓷御器终极奖励发送
    """

    def __init__(self, activity_id):
        self.activity_adapter = cross_adt.CrossCeladonActivityAdapter
        self.record_adapter = cross_adt.CrossCeladonRoleAdapter  # 标记是否领取奖励的适配器
        self.activity_id = activity_id
        self.activity = self.activity_adapter.objects.get(ActivityId=self.activity_id)
        self.activity_class = ActivityClass.CrossCeladon

    ###############################################

    def is_not_award(self, rid):
        return self.record_adapter.objects.get(RoleGuid=rid, ActivityId=self.activity_id, IsGetFinalAward=0)

    def set_record_has_award(self, rid):
        """设置记录为已领取"""
        self.record_adapter.objects.filter(RoleGuid=rid, ActivityId=self.activity_id).update(IsGetFinalAward=2)

    def get_activity_name(self):
        """获取活动名称"""
        # 从TcActivityType表中获取活动名称
        env_key = getProfile('TcActivityType', Class=self.activity_class).LangEnvKey
        return getattr(GameConfigEnvLang(), env_key)

    def get_award(self):
        """获取活动奖励配置"""
        return self.activity.final_award_list

    def get_rank_key(self):
        """获取榜单Key"""
        # 获取榜单数据
        rank_key = share_leader_board_component.fill_leader_board_key(CrossCeladonRankKey.PersonRankKey,
                                                                      act_id=self.activity_id)
        return rank_key

    def get_gainer_info(self):
        """
        获取终极奖励获得者
        :return: {[rid, score, server_id]}
        """
        gainer_info = FinalAwardCommon.has_final_award_by_type(ActivityType.CrossCeladon, self.get_rank_key())
        return gainer_info

    @property
    def content(self):
        return getattr(GameConfigEnvLang(), 'CrossCeladonFinalAwardContent')

    @property
    def subject(self):
        return getattr(GameConfigEnvLang(), 'ActivityMailSubject')

    def get_content(self):
        name_lang = self.get_activity_name()
        content = {}
        for code, msg in self.content.items():
            content[code] = msg.format(name=name_lang[code])

        return content

    def get_subject(self):
        name_lang = self.get_activity_name()
        subject = {}
        for code, msg in self.subject.items():
            subject[code] = msg.format(name=name_lang[code])

        return subject

    def send_award(self):
        """
        执行发奖
        外部只需要调用该方法就可完成发奖
        :return:
        """
        # 获取获得者
        gainer_info = self.get_gainer_info()
        if gainer_info:
            rid, score, server_id = gainer_info     # 获得者信息
            # 设置上下文
            with temporary_ctx(server_id=server_id):
                if self.is_not_award(rid):
                    # 邮件奖励说明
                    content = self.get_content()
                    subject = self.get_subject()
                    # 发送奖励邮件
                    service_id = RoleRepository.get_by_rid(rid, "ServiceId").service_id
                    # 调用区服服务发送活动奖励
                    res_data = AreaSendActivityService.send_rank_activity_award_mail([service_id],
                                                                                     self.get_award(),
                                                                                     subject, content, server_id)
                    # 设置已经领取
                    if res_data and 'Success' in res_data:
                        if service_id in res_data["Success"]:
                            self.set_record_has_award(rid)
        return


class CrossFightSendPeakAward(RankActivitySendAwardBase):
    """
    皇决之选--巅峰赛榜单奖励发送
    """

    def __init__(self, activity_id):
        self.activity_adapter = cross_adt.CrossFightRegionAdapter
        self.award_adapter = cross_adt.CrossFightAwardActivityCfgAdapter  # 活动映射适配器
        self.record_adapter = cross_adt.CrossFightActivityRoleAdapter  # 标记是否领取奖励的适配器
        self.fight_adapter = cross_adt.CrossFightTimeActivityAdapter  # 标记活动
        super(CrossFightSendPeakAward, self).__init__(activity_id)
        self.fight_activity = self.get_fight_activity()
        self.fight_award = self.get_fight_award()
        self.activity_class = ActivityClass.CrossFight

    ###############################################

    def get_fight_activity(self):
        """
        返回pvp适配器实例
        :return:
        """
        if self.fight_adapter is None:
            raise Exception('fight_adapter of RankActivitySendAward is None')
        return self.fight_adapter.objects.get(FightId=self.activity.fight_id)

    def get_fight_award(self):
        """
        返回皇决之选活动适配器实例
        :return:
        """
        return self.award_adapter.objects.get(TemplateId=self.fight_activity.template_id,
                                              MatchId=CrossFightMatch.Peak)

    def get_not_award_record_list(self, rid_list, server_id):
        return self.record_adapter.objects.filter(RoleGuid__in=rid_list, ActivityId=self.activity_id, HasPeakAward=0)

    def set_record_has_award(self, rid_list, server_id):
        """设置记录为已领取"""
        self.record_adapter.objects.filter(RoleGuid__in=rid_list, ActivityId=self.activity_id).update(HasPeakAward=1)

    def get_activity_range_cfg(self):
        """获取排名奖励区间配置"""
        return self.fight_award.range_list

    def get_activity_name(self):
        """获取活动名称"""
        # 从TcActivityType表中获取活动名称
        env_key = getProfile('TcActivityType', Class=self.activity_class).LangEnvKey
        return getattr(GameConfigEnvLang(), env_key)

    def get_award_list_cfg(self):
        """获取活动奖励配置"""
        return self.fight_award.award_list

    def get_rank_key(self):
        """获取榜单key"""
        return CrossFightRankType.Peak

    def get_rank_list(self, *args, **kwargs):
        """获取榜单"""
        start, end = self.get_start_end()
        # 获取榜单数据
        rank_data = cross_fight_rank_component.get_rank_list(self.get_rank_key(), self.activity_id, start=start,
                                                             end=end, group_id=1)
        return rank_data

    def get_rank_award_cfg(self, rank, score=0):
        """
        返回排名对应的奖励配置
        :param rank: 排名
        :param score: 分数
        :return:
        """
        award_index = self.rank_to_award_index(rank)
        if award_index not in self.award_id_dict:
            self.award_id_dict[award_index] = create_idx()
        award_list = self.get_award_list_cfg()[award_index]

        # 判断是否有额外奖励可领取
        extra_award_list = []
        if award_index < len(self.fight_award.extra_score_list):
            if ((score >= self.fight_award.extra_score_list[award_index])
                    and award_index < len(self.fight_award.extra_award_list)):
                extra_award_list = self.fight_award.extra_award_list[award_index]
        # 拼接最终下发奖励
        if extra_award_list:
            award_list += extra_award_list
        return award_list, award_index, self.award_id_dict[award_index]

    def get_rank_data(self):
        """
        初始化
        :return:
        """

        rank_data = self.get_rank_list()
        # [nick_name, score, server_id, rid, small_head_id, head_frame_id, head_id, last_season_dan]
        for index, data in enumerate(rank_data):
            self.server_for_rids[data[2]].append(data[3])
            self.rid_for_rank[data[3]] = index + 1

    @property
    def content(self):
        return getattr(GameConfigEnvLang(), 'CrossFightPeakRankContent')

    def get_extra_award_list_cfg(self):
        """获取活动额外奖励配置"""
        return self.fight_award.extra_award_list

    def get_extra_score_list_cfg(self):
        """获取活动额外积分配置"""
        return self.fight_award.extra_score_list

    def send_single_person_award(self, service_id_dict, rank_dict, server_id):
        """
        发送奖励
        个人排行奖励
        :return:
        """

        for rank, record_list in rank_dict.iteritems():
            # 邮件奖励说明
            content = self.get_content(rank)
            subject = self.get_subject()
            score = 0  # 玩家分数
            if record_list:
                fight_role = record_list[0]
                score = fight_role.person_score
            # 排行奖励
            award_list, index, award_id = self.get_rank_award_cfg(rank, score)

            s_id_to_role_id_dict = {service_id_dict.get(r.role_guid): r.role_guid for r in record_list}
            # 调用区服服务发送活动奖励
            res_data = AreaSendActivityService.send_rank_activity_award_mail(s_id_to_role_id_dict.keys(), award_list,
                                                                             subject, content, server_id)

            self.response_callback(res_data, s_id_to_role_id_dict, server_id)


class CrossFightSendReputationAward(CrossFightSendPeakAward):
    """
    皇决之选--巅峰赛人气榜单奖励发送
    """
    def get_fight_award(self):
        """
        返回皇决之选活动适配器实例
        :return:
        """
        return self.award_adapter.objects.get(TemplateId=self.fight_activity.template_id,
                                              MatchId=CrossFightRankType.Reputation)

    def get_not_award_record_list(self, rid_list, server_id):
        return self.record_adapter.objects.filter(RoleGuid__in=rid_list, ActivityId=self.activity_id, HasReputationAward=0)

    def set_record_has_award(self, rid_list, server_id):
        """设置记录为已领取"""
        self.record_adapter.objects.filter(RoleGuid__in=rid_list, ActivityId=self.activity_id).update(HasPeakAward=1)

    def get_rank_key(self):
        """获取榜单key"""
        return CrossFightRankType.Reputation

    def get_rank_list(self, *args, **kwargs):
        """获取榜单"""
        start, end = self.get_start_end()
        # 获取榜单数据
        rank_data = cross_fight_rank_component.get_rank_list(self.get_rank_key(), self.activity_id, start=start,
                                                             end=end)
        return rank_data

    @property
    def content(self):
        return getattr(GameConfigEnvLang(), 'CrossFightReputationRankContent')

    def send_single_person_award(self, service_id_dict, rank_dict, server_id):
        """
        发送奖励
        个人排行奖励
        :return:
        """

        for rank, record_list in rank_dict.iteritems():
            # 邮件奖励说明
            content = self.get_content(rank)
            subject = self.get_subject()
            score = 0  # 玩家分数
            if record_list:
                fight_role = record_list[0]
                score = fight_role.reputation
            # 排行奖励
            award_list, index, award_id = self.get_rank_award_cfg(rank, score)

            s_id_to_role_id_dict = {service_id_dict.get(r.role_guid): r.role_guid for r in record_list}
            # 调用区服服务发送活动奖励
            res_data = AreaSendActivityService.send_rank_activity_award_mail(s_id_to_role_id_dict.keys(), award_list,
                                                                             subject, content, server_id)

            self.response_callback(res_data, s_id_to_role_id_dict, server_id)


class CrossTowerSendAward(RankActivitySendAwardBase):
    """
    跨服爬塔个人榜单奖励发送
    """

    def __init__(self, activity_id):
        self.activity_adapter = cross_adt.CrossTowerActivityAdapter
        self.record_adapter = cross_adt.CrossTowerRoleAdapter  # 标记是否领取奖励的适配器
        super(CrossTowerSendAward, self).__init__(activity_id)
        self.activity_class = ActivityClass.CrossTower

    ###############################################

    def get_not_award_record_list(self, rid_list, server_id):
        return self.record_adapter.objects.filter(RoleGuid__in=rid_list, ActivityId=self.activity_id, IsGetPersonAward=0)

    def set_record_has_award(self, rid_list, server_id):
        """设置记录为已领取"""
        self.record_adapter.objects.filter(RoleGuid__in=rid_list, ActivityId=self.activity_id).update(IsGetPersonAward=2)

    def get_activity_range_cfg(self):
        """获取排名奖励区间配置"""
        return self.activity.person_range_list

    def get_activity_name(self):
        """获取活动名称"""
        # 从TcActivityType表中获取活动名称
        env_key = getProfile('TcActivityType', Class=self.activity_class).LangEnvKey
        return getattr(GameConfigEnvLang(), env_key)

    def get_award_list_cfg(self):
        """获取活动奖励配置"""
        return self.activity.person_award_list

    def get_rank_key(self):
        """获取榜单key"""
        return CrossTowerRankKey.PersonRankKey

    def get_rank_list(self, *args, **kwargs):
        """获取榜单"""
        start, end = self.get_start_end()
        # 获取榜单数据
        rank_key = share_leader_board_component.fill_leader_board_key(self.get_rank_key(),
                                                                      act_id=self.activity_id)
        rank_data = share_leader_board_component.get_rank_range(rank_key, start, end, 0,
                                                                share_leader_board_component.RankType.RoleRank)
        return rank_data

    def send_single_person_award(self, service_id_dict, rank_dict, server_id):
        """
        发送奖励
        个人排行奖励
        :return:
        """

        for rank, record_list in rank_dict.iteritems():
            # 邮件奖励说明
            content = self.get_content(rank)
            subject = self.get_subject()
            score = 0  # 玩家分数
            if record_list:
                tower_role = record_list[0]
                score = tower_role.floor
            award_list, index, award_id = self.get_rank_award_cfg(rank, score)
            s_id_to_role_id_dict = {service_id_dict.get(r.role_guid): r.role_guid for r in record_list}
            # 调用区服服务发送活动奖励
            res_data = AreaSendActivityService.send_rank_activity_award_mail(s_id_to_role_id_dict.keys(), award_list,
                                                                             subject, content, server_id)

            self.response_callback(res_data, s_id_to_role_id_dict, server_id)

    def get_rank_award_cfg(self, rank, score=0):
        """
        返回排名对应的奖励配置
        :param rank: 排名
        :param score: 需求积分
        :return:
        """
        award_index = self.rank_to_award_index(rank)
        if award_index not in self.award_id_dict:
            self.award_id_dict[award_index] = create_idx()
        award_list = self.get_award_list_cfg()[award_index]

        # 判断是否有额外奖励可领取
        extra_award_list = []
        if award_index < len(self.activity.person_extra_score_list):
            if ((score >= self.activity.person_extra_score_list[award_index])
                    and award_index < len(self.activity.person_extra_award_list)):
                extra_award_list = self.activity.person_extra_award_list[award_index]
        # 拼接最终下发奖励
        if extra_award_list:
            award_list += extra_award_list
        return award_list, award_index, self.award_id_dict[award_index]

    def get_rank_data(self):
        """
        初始化  {role_id: 排名}
        :return: {rid: [rank, server_id]}
        """

        rank_data = self.get_rank_list()

        for index, data in enumerate(rank_data):
            self.server_for_rids[data[2]].append(data[0])
            self.rid_for_rank[data[0]] = index + 1

    @property
    def content(self):
        return getattr(GameConfigEnvLang(), 'CrossTowerPersonRankContent')


class CrossTowerSendFinalAward(object):
    """
    跨服爬塔终极奖励发送
    """

    def __init__(self, activity_id):
        self.activity_adapter = cross_adt.CrossTowerActivityAdapter
        self.record_adapter = cross_adt.CrossTowerRoleAdapter  # 标记是否领取奖励的适配器
        self.activity_id = activity_id
        self.activity = self.activity_adapter.objects.get(ActivityId=self.activity_id)
        self.activity_class = ActivityClass.CrossTower

    ###############################################

    def is_not_award(self, rid):
        return self.record_adapter.objects.get(RoleGuid=rid, ActivityId=self.activity_id, IsGetFinalAward=0)

    def set_record_has_award(self, rid):
        """设置记录为已领取"""
        self.record_adapter.objects.filter(RoleGuid=rid, ActivityId=self.activity_id).update(IsGetFinalAward=2)

    def get_activity_name(self):
        """获取活动名称"""
        # 从TcActivityType表中获取活动名称
        env_key = getProfile('TcActivityType', Class=self.activity_class).LangEnvKey
        return getattr(GameConfigEnvLang(), env_key)

    def get_award(self):
        """获取活动奖励配置"""
        return self.activity.final_award_list

    def get_rank_key(self):
        """获取榜单Key"""
        # 获取榜单数据
        rank_key = share_leader_board_component.fill_leader_board_key(CrossTowerRankKey.PersonRankKey,
                                                                      act_id=self.activity_id)
        return rank_key

    def get_gainer_info(self):
        """
        获取终极奖励获得者
        :return: {[rid, score, server_id]}
        """
        gainer_info = FinalAwardCommon.has_final_award_by_type(ActivityType.CrossTower, self.get_rank_key())
        return gainer_info

    @property
    def content(self):
        return getattr(GameConfigEnvLang(), 'CrossTowerFinalAwardContent')

    @property
    def subject(self):
        return getattr(GameConfigEnvLang(), 'ActivityMailSubject')

    def get_content(self):
        name_lang = self.get_activity_name()
        content = {}
        for code, msg in self.content.items():
            content[code] = msg.format(name=name_lang[code])

        return content

    def get_subject(self):
        name_lang = self.get_activity_name()
        subject = {}
        for code, msg in self.subject.items():
            subject[code] = msg.format(name=name_lang[code])

        return subject

    def send_award(self):
        """
        执行发奖
        外部只需要调用该方法就可完成发奖
        :return:
        """
        # 获取获得者
        gainer_info = self.get_gainer_info()
        if gainer_info:
            rid, score, server_id = gainer_info     # 获得者信息
            # 设置上下文
            with temporary_ctx(server_id=server_id):
                if self.is_not_award(rid):
                    # 邮件奖励说明
                    content = self.get_content()
                    subject = self.get_subject()
                    # 发送奖励邮件
                    service_id = RoleRepository.get_by_rid(rid, "ServiceId").service_id
                    # 调用区服服务发送活动奖励
                    res_data = AreaSendActivityService.send_rank_activity_award_mail([service_id],
                                                                                     self.get_award(),
                                                                                     subject, content, server_id)
                    # 设置已经领取
                    if res_data and 'Success' in res_data:
                        if service_id in res_data["Success"]:
                            self.set_record_has_award(rid)
        return


class CrossFishPersonSendAward(RankActivitySendAwardBase):
    """
    跨服御海垂纶个人单局榜单奖励发送
    """
    def __init__(self, activity_id):
        self.activity_adapter = cross_adt.CrossFishActivityAdapter
        self.record_adapter = cross_adt.CrossFishRoleAdapter  # 标记是否领取奖励的适配器
        super(CrossFishPersonSendAward, self).__init__(activity_id)
        self.activity_class = ActivityClass.CrossFish

    def get_not_award_record_list(self, rid_list, server_id):
        return self.record_adapter.objects.filter(RoleGuid__in=rid_list,
                                                  ActivityId=self.activity_id, IsGetPersonAward=0)

    def set_record_has_award(self, rid_list, server_id):
        """设置记录为已领取"""
        self.record_adapter.objects.filter(RoleGuid__in=rid_list,
                                           ActivityId=self.activity_id).update(IsGetPersonAward=2)

    def get_activity_range_cfg(self):
        """获取排名奖励区间配置"""
        return self.activity.person_range_list

    def get_activity_name(self):
        """获取活动名称"""
        # 从TcActivityType表中获取活动名称
        env_key = getProfile('TcActivityType', Class=self.activity_class).LangEnvKey
        return getattr(GameConfigEnvLang(), env_key)

    def get_award_list_cfg(self):
        """获取活动奖励配置"""
        return self.activity.person_award_list

    def get_rank_key(self):
        """获取榜单key"""
        return CrossFishRankKey.MaxPersonScore

    def get_rank_list(self, *args, **kwargs):
        """获取榜单"""
        start, end = self.get_start_end()
        # 获取榜单数据
        rank_key = share_leader_board_component.fill_leader_board_key(self.get_rank_key(),
                                                                      act_id=self.activity_id)
        rank_data = share_leader_board_component.get_rank_range(rank_key, start, end, 0,
                                                                share_leader_board_component.RankType.RoleRank)
        return rank_data

    def get_rank_award_cfg(self, rank, score=0):
        """
        返回排名对应的奖励配置
        :param rank: 排名
        :param score: 排名
        :return:
        """
        award_index = self.rank_to_award_index(rank)
        if award_index not in self.award_id_dict:
            self.award_id_dict[award_index] = create_idx()
        award_list = self.get_award_list_cfg()[award_index]

        # 判断是否有额外奖励可领取
        extra_award_list = []
        if award_index < len(self.activity.person_extra_score_list):
            if ((score >= self.activity.person_extra_score_list[award_index])
                    and award_index < len(self.activity.person_extra_award_list)):
                extra_award_list = self.activity.person_extra_award_list[award_index]
        # 拼接最终下发奖励
        if extra_award_list:
            award_list += extra_award_list
        return award_list, award_index, self.award_id_dict[award_index]

    def get_rank_data(self):
        """
        初始化  {role_id: 排名}
        :return: {rid: [rank, server_id]}
        """
        rank_data = self.get_rank_list()
        for index, data in enumerate(rank_data):
            self.server_for_rids[data[2]].append(data[0])
            self.rid_for_rank[data[0]] = index + 1

    def send_single_person_award(self, service_id_dict, rank_dict, server_id):
        """
        发送奖励
        :return:
        """
        for rank, record_list in rank_dict.iteritems():
            # 邮件奖励说明
            content = self.get_content(rank)
            subject = self.get_subject()
            score = 0  # 玩家分数
            if record_list:
                fish_role = record_list[0]
                score = fish_role.max_person_score
            award_list, index, award_id = self.get_rank_award_cfg(rank, score)
            s_id_to_role_id_dict = {service_id_dict.get(r.role_guid): r.role_guid for r in record_list}
            # 调用区服服务发送活动奖励
            res_data = AreaSendActivityService.send_rank_activity_award_mail(s_id_to_role_id_dict.keys(), award_list,
                                                                             subject, content, server_id)

            self.response_callback(res_data, s_id_to_role_id_dict, server_id)

    @property
    def content(self):
        return getattr(GameConfigEnvLang(), 'CrossFishPersonRankContent')


class CrossFishActiveSendAward(RankActivitySendAwardBase):
    """
    跨服御海垂纶个人累计榜单奖励发送
    """
    def __init__(self, activity_id):
        self.activity_adapter = cross_adt.CrossFishActivityAdapter
        self.record_adapter = cross_adt.CrossFishRoleAdapter  # 标记是否领取奖励的适配器
        super(CrossFishActiveSendAward, self).__init__(activity_id)
        self.activity_class = ActivityClass.CrossFish

    def get_not_award_record_list(self, rid_list, server_id):
        return self.record_adapter.objects.filter(RoleGuid__in=rid_list,
                                                  ActivityId=self.activity_id, IsGetTotalAward=0)

    def set_record_has_award(self, rid_list, server_id):
        """设置记录为已领取"""
        self.record_adapter.objects.filter(RoleGuid__in=rid_list,
                                           ActivityId=self.activity_id).update(IsGetTotalAward=2)

    def get_activity_range_cfg(self):
        """获取排名奖励区间配置"""
        return self.activity.active_range_list

    def get_activity_name(self):
        """获取活动名称"""
        # 从TcActivityType表中获取活动名称
        env_key = getProfile('TcActivityType', Class=self.activity_class).LangEnvKey
        return getattr(GameConfigEnvLang(), env_key)

    def get_award_list_cfg(self):
        """获取活动奖励配置"""
        return self.activity.active_award_list

    def get_rank_key(self):
        """获取榜单key"""
        return CrossFishRankKey.ActivePersonScore

    def get_rank_list(self, *args, **kwargs):
        """获取榜单"""
        start, end = self.get_start_end()
        # 获取榜单数据
        rank_key = share_leader_board_component.fill_leader_board_key(self.get_rank_key(),
                                                                      act_id=self.activity_id)
        rank_data = share_leader_board_component.get_rank_range(rank_key, start, end, 0,
                                                                share_leader_board_component.RankType.RoleRank)
        return rank_data

    def get_rank_award_cfg(self, rank, score=0):
        """
        返回排名对应的奖励配置
        :param rank: 排名
        :param score: 排名
        :return:
        """
        award_index = self.rank_to_award_index(rank)
        if award_index not in self.award_id_dict:
            self.award_id_dict[award_index] = create_idx()
        award_list = self.get_award_list_cfg()[award_index]

        # 判断是否有额外奖励可领取
        extra_award_list = []
        if award_index < len(self.activity.active_extra_score_list):
            if ((score >= self.activity.active_extra_score_list[award_index])
                    and award_index < len(self.activity.active_extra_award_list)):
                extra_award_list = self.activity.active_extra_award_list[award_index]
        # 拼接最终下发奖励
        if extra_award_list:
            award_list += extra_award_list
        return award_list, award_index, self.award_id_dict[award_index]

    def get_rank_data(self):
        """
        初始化  {role_id: 排名}
        :return: {rid: [rank, server_id]}
        """
        rank_data = self.get_rank_list()
        for index, data in enumerate(rank_data):
            self.server_for_rids[data[2]].append(data[0])
            self.rid_for_rank[data[0]] = index + 1

    def send_single_person_award(self, service_id_dict, rank_dict, server_id):
        """
        发送奖励
        :return:
        """
        for rank, record_list in rank_dict.iteritems():
            # 邮件奖励说明
            content = self.get_content(rank)
            subject = self.get_subject()
            score = 0  # 玩家分数
            if record_list:
                fish_role = record_list[0]
                score = fish_role.active_person_score
            award_list, index, award_id = self.get_rank_award_cfg(rank, score)
            s_id_to_role_id_dict = {service_id_dict.get(r.role_guid): r.role_guid for r in record_list}
            # 调用区服服务发送活动奖励
            res_data = AreaSendActivityService.send_rank_activity_award_mail(s_id_to_role_id_dict.keys(), award_list,
                                                                             subject, content, server_id)

            self.response_callback(res_data, s_id_to_role_id_dict, server_id)

    @property
    def content(self):
        return getattr(GameConfigEnvLang(), 'CrossFishActiveRankContent')
